define(['app','angular'], function( app ) {
'use strict';

/*window.onerror = function(errorMessage, scriptURI, lineNumber,columnNumber,errorObj) {
    var ustr = sessionStorage.getItem("user");
    var udata = JSON.parse( ustr );
    var uid = 0;
    console.log( errorMessage );
   return true;
}*/
console.log( angular );
console.log( app );
app.factory('account', function ($q, appFactory, dataFactoryCRM) {
    var account = {};

    account.login = function (username, password, captioncode ) {
        var deferred = $q.defer();
        sessionStorage.showHomeNotify = 0;
        appFactory.login(username, password, captioncode ).then(function (response) {

            sessionStorage.token = response["data"]["user_id"]; //temporally use user_no as Token
            sessionStorage.username = response["data"]["nickname"];
            sessionStorage.user = JSON.stringify(response["data"] ) ; //storage只能存储字符串的数据
            deferred.resolve();

        }, function (error) {
            deferred.reject(error);
        });

        return deferred.promise;
    }

    account.logout = function () {
        return appFactory.logout().then(function () {
            account.clear();
        })
    }

    account.clear = function () {
        dataFactoryCRM.destroyCache(); //注销时清理数据缓存
        sessionStorage.clear();
    }

    account.getToken = function () {
        return sessionStorage.token;
    }

    account.getUsername = function () {
        return sessionStorage.username;
    }

    account.getUser = function () {
        if (sessionStorage.user) {
            return sessionStorage.user ? JSON.parse( sessionStorage.user  ) : null;
        } else
            return null;
    }

    account.isConnected = function () {
        if (sessionStorage.token)
            return true;

        return false;
    }

    return account;
});

//AnimeDataService API
app.factory('dataFactoryCRM', function ($http, $sce, $cacheFactory, $q, DSCacheFactory, crmConst) {
    var dataFactory = {};

    //Prepare caching for better user experience
    DSCacheFactory('dataCache', {
        maxAge: 900000, // Items added to this cache expire after 15 minutes.
        cacheFlushInterval: 6000000, // This cache will clear itself every hour.
        deleteOnExpire: 'aggressive', // Items will be deleted from this cache right when they expire.
        storageMode: 'memory' // [default: memory] sessionStorage, localStorage
    });

    dataFactory.checkForInternetConnection = function (callback) {
        $http.get( crmConst.BASE ).success(function (data) {
            callback(true);
        }).error(function (e) {
            callback(false);
        });
    }

    dataFactory.isServiceOnline = function (callback) {
        $http.get( crmConst.BASE + "ifServiceReady").success(function (data) {
            callback(true);
        })
            .error(function (data, status) {
                if (status == 401)
                    callback(true);
                else
                    callback(false);
            });
    }
    dataFactory.postDataByAPI = function( api_url, _data){
        var query = crmConst.BASE + crmConst.API + api_url;
        var deferred = $q.defer();
        $http({
            method: 'POST',
            url: query,
            data: _data,
            headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
        }).success(function (response, status, headers, config) {
                if (status == 200) {
                    deferred.resolve(response);
                } else {
                    console.log(status);
                    deferred.reject(response);
                }
            })
            .error(function (error) {
                console.log(error);
                deferred.reject(error);
            });

         return deferred.promise;
    }

     dataFactory.getDataByAPI = function (api_url, do_not_cache) {

        var filter,
            deferred = $q.defer(),
            dataCache = DSCacheFactory.get('dataCache');

        var query = crmConst.BASE + crmConst.API  + api_url;

        var ustr = sessionStorage.getItem("user");
        var udata = JSON.parse( ustr );
        var uid = 0;
        if( udata && udata.uid ){ uid = udata.uid; }

        if (!do_not_cache && dataCache.get(query) && 0) {
            deferred.resolve(dataCache.get(query));
        } else {
            //Only animes with vk available
            $http.get(query )
                .success(function (data) {
                    if (!do_not_cache) {
                        dataCache.put(query, data);
                        //console.log('cache:' + query);
                      }
                    deferred.resolve(data);
                }).error(function (error , status ) {
                    deferred.reject();
            });
        }

        return deferred.promise;
    }

//重写
     dataFactory.getDataByAPIS = function (api_url,do_not_cache) {

        var filter,
            deferred = $q.defer(),
            dataCache = DSCacheFactory.get('dataCache');

        var query = crmConst.BASE + crmConst.API  + api_url;

        var ustr = sessionStorage.getItem("user");
        var udata = JSON.parse( ustr );
        var uid = 0;
        if( udata && udata.uid ){ uid = udata.uid; }

        if (!do_not_cache && dataCache.get(query) && 0) {
            deferred.resolve(dataCache.get(query));
        } else {
            //Only animes with vk available
            $http.get(query,{ responseType: "arraybuffer" })
                .success(function (data) {
                    if (!do_not_cache) {
                        dataCache.put(query, data);
                        //console.log('cache:' + query);
                      }
                    deferred.resolve(data);
                }).error(function (error , status ) {
                    deferred.reject();
            });
        }

        return deferred.promise;
    }



	dataFactory.destroyCache = function () {
        DSCacheFactory.clearAll();
  }
    return dataFactory;
});

//appService API
app.factory('appFactory', function ($http, $q, crmConst) {
    var rootFactory = {};

    //Login
    rootFactory.login = function (username, password, caption) {
        var loginUrl = crmConst.BASE + crmConst.API + 'login';
        var deferred = $q.defer();

        //Send login
        var formData = "username=" + username + "&password=" + password + "&caption=" + caption ;

        $http({
            method: 'POST',
            url: loginUrl,
            data: formData,
            headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
        }).success(function (response, status, headers, config) {
                if (status == 200) {
                    deferred.resolve(response);
                } else {
                    console.log(status);
                    deferred.reject(response);
                }
            })
            .error(function (error) {
                console.log(error);
                deferred.reject(error);
            });

         return deferred.promise;
    }

    //LogOut
    rootFactory.logout = function () {
        var logoutUrl = crmConst.BASE + crmConst.API  + 'login/logout';
        var deferred = $q.defer();

        //Send logOut
        $http.get(logoutUrl )
            .success(function (response, status, headers, config) {
                if (status == 200) {
                    deferred.resolve(response);
                } else {
                    deferred.reject(response);
                }
            })
            .error(function (error) {
                console.log(error);
                deferred.reject(error);
            });

        return deferred.promise;
    }

    //Check if service is available
    rootFactory.isServiceOnline = function (callback) {
        $http.get( crmConst.BASE ).success(function (data) {
            callback(true);
        })
            .error(function (data, status) {
                callback(false);
            });
    }

    return rootFactory;
});

});